Thread: Return five first digits out of a random number

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    8

    Return five first digits out of a random number

    How can I get the first 5 digits in a random length integer?

    For example: users input 1234567, 123456789, 1012345671

    I should get 12345, 12345, 10123 respectively.
    The number input by an user is not known in advance.

  2. #2
    Registered User
    Join Date
    Jul 2010
    Posts
    26
    Keep dividing the number by 10 until you get something <= 99999.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    If you're fairly sure that the user will enter numbers sensibly and not with e.g. leading spaces, you could just read the input as a string and get the first five characters. That's a bit of a hack though and so I also echo qwertylurker's suggestion.
    Code:
    while(n >= 100000) n /= 10;
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    8
    Ok, thanks for the tip qwertylurker and dwks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  2. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. problem with open gl engine.
    By gell10 in forum Game Programming
    Replies: 1
    Last Post: 08-21-2003, 04:10 AM
  5. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 07:48 PM